const state = {
	goodsList: uni.getStorageSync('goodsList')
		? JSON.parse(uni.getStorageSync('goodsList'))
		: [],
};
const mutations = {
	// 添加商品到购物车
	addGoods: (state, data) => {
		const { shopExist, shopIndex, value } = data;

		if (shopExist === true) {
			state.goodsList[shopIndex].product.unshift(value);
		} else {
			state.goodsList.unshift(value);
		}

		uni.setStorageSync('goodsList', JSON.stringify(state.goodsList));
	},
	// 购物车删除
	deleteGoods: (state, id) => {
		if (id) {
			for (let i = state.goodsList.length - 1; i > -1; i--) {
				if (state.goodsList[i].id === id) {
					if (state.goodsList[i].checked === true) {
						state.goodsList.splice(i, 1);
					} else {
						for (let j = state.goodsList[i].product.length - 1; j > -1; j--) {
							if (state.goodsList[i].product[j].checked === true) {
								state.goodsList[i].product.splice(j, 1);
							}
						}
					}
				}
			}
		} else {
			for (let i = state.goodsList.length - 1; i > -1; i--) {
				if (state.goodsList[i].checked === true) {
					state.goodsList.splice(i, 1);
				} else {
					for (let j = state.goodsList[i].product.length - 1; j > -1; j--) {
						if (state.goodsList[i].product[j].checked === true) {
							state.goodsList[i].product.splice(j, 1);
						}
					}
				}
			}
		}
		uni.setStorageSync('goodsList', JSON.stringify(state.goodsList));
	},
	// 全选。全不选
	allCheck: (state, value) => {
		state.goodsList.map(function (item) {
			item.checked = value;
			item.product.map(function (itemProduct) {
				itemProduct.checked = value;
				return itemProduct;
			});
		});
		uni.setStorageSync('goodsList', JSON.stringify(state.goodsList));
	},
	// 选择店铺
	shopCheck: (state, data) => {
		const { index, key, value } = data;
		state.goodsList[index][key] = value;
		state.goodsList[index].product.map((item) => {
			item.checked = value;
			return item;
		});
		uni.setStorageSync('goodsList', JSON.stringify(state.goodsList));
	},
	// 选择商品
	productCheck: (state, data) => {
		const { productIndex, index, key, value } = data;
		state.goodsList[index].product[productIndex][key] = value;
		state.goodsList[index].product.every(function (item) {
			return item.checked === true;
		})
			? (state.goodsList[index][key] = true)
			: (state.goodsList[index][key] = false);

		uni.setStorageSync('goodsList', JSON.stringify(state.goodsList));
	},
};
export default {
	state,
	mutations,
};
